package com.sakura.acl.service.impl;


import cn.hutool.json.JSONUtil;
import com.sakura.acl.entity.User;
import com.sakura.acl.service.PermissionService;
import com.sakura.acl.service.UserService;
import com.sakura.commonutils.key.UserKey;
import com.sakura.security.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 自定义userDetailsService - 认证用户详情
 *
 * @author Sakura
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RedisTemplate redisTemplate;



    /***
     * 根据账号获取用户信息
     * @param username:
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        User user = userService.selectByUsername(username);
        //将数据库中的数据存储到redis缓存中并设置存活时间为1小时
        redisTemplate.opsForValue().set(UserKey.getUserInfo()+username,
                user,1, TimeUnit.HOURS);

        // 判断用户是否存在
        if (null == user){
            throw new UsernameNotFoundException("用户名不存在！");
        }
        // 返回UserDetails实现类
        com.sakura.security.entity.User curUser = new com.sakura.security.entity.User();
        BeanUtils.copyProperties(user,curUser);

        //获取该用户的权限列表
        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        //同时将该用户的权限列表信息也存储在redis缓存中
        redisTemplate.opsForValue().set(UserKey.getUserPermissionList()+username,
                authorities,1,TimeUnit.HOURS);

        SecurityUser securityUser = new SecurityUser(curUser);
        securityUser.setPermissionValueList(authorities);
        return securityUser;
    }



}
